import random
import re
from information import redis_store
from information.libs.yuntongxun.sms import CCP
from information.utils.captcha.captcha import captcha
from information.utils.response_code import RET
from . import passport_blu
from flask import render_template, abort, current_app, make_response, jsonify, json, request, redirect, url_for
from information.utils.encryption import encry_md5
from .. import data
sms_code=444444

@passport_blu.route('/image_code',methods=['GET'])
def get_image_code():
    """
    生成图片验证码并返回
    1.取到参数
    2.判断参数是否有值
    3.生成图片验证码
    4.保存图片验证码文字内容到redis
    5.返回验证码图片
    ：return：
    """
    #1.取到参数
    #arg：取到url中？后面的参数
    image_code_id=request.args.get('imageCodeId')
    #2.判断参数是否有值
    if not image_code_id:
        abort(403)
    # 生成图片验证码，其返回为名字、文本、以及图片
    name,text,image=captcha.generate_captcha()
    print(text)
    # print("图片验证码是：{}".format(text))
    # print(image_code_id)
    # 将图形验证码保存到redis数据库中
    try:
        redis_store.set('ImageCode_' + image_code_id,text, 300 )
    except Exception as e:
        current_app.logger.error(e)
    response=make_response(image)
    response.headers['Content-Type']='image/png'
    return response

@passport_blu.route('/sms_code',methods=['POST'])
def send_ssm_code():
    params_dict=request.json
    #params_dict = request.get_json()
    #params_dict=json.loads(request.get_data())
    #print(params_dict)
    mobile=params_dict.get('mobile')
    #print(mobile)
    image_code = params_dict.get('image_code')
    image_code_id = params_dict.get('image_code_id')
    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数有误')
    if not re.match('1[35678]\\d{9}',mobile):
        return jsonify(errno=RET.PARAMERR,errmsg='手机号有误')
    real_image_code=''
    try:
        real_image_code=redis_store.get('ImageCode_' + image_code_id)
        real_image_code=real_image_code.decode()
        # print(real_image_code)
        # print(type(real_image_code))
    except Exception as e:
        current_app.looger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg='验证码过期')
    if image_code!=real_image_code:
        return jsonify(errno=RET.PARAMERR, errmsg='验证码错误')
    global sms_code
    sms_code='%6d'%random.randint(0,999999)
    ccp = CCP()
    # 注意： 测试的短信模板编号为1
    result=ccp.send_template_sms(mobile, [sms_code, 5], 1)
    if result!=0:
        return jsonify(errno=RET.THIRDERR, errmsg='第三方系统错误')
    try:
        redis_store.set('SMSCode_'+sms_code,sms_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    return jsonify(errno=RET.OK, errmsg='短信验证码发送成功')

@passport_blu.route('/register',methods=['POST'])
def register():
    params_dict=request.json
    mobile = params_dict.get('mobile')
    smscode = params_dict.get('smscode')
    password = params_dict.get('password')
    print(params_dict,sms_code,type(mobile))
    from information.utils.models import User
    from information import db
    if not all([mobile,smscode,password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')
    if int(smscode)!=sms_code:
        return jsonify(errno=RET.PARAMERR, errmsg='输入手机验证码错误')
    user=User.query.filter_by(mobile=mobile).first()
    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg='该手机号已被注册')
    try:
        user1=User(mobile=mobile,password_hash=encry_md5(password),nick_name='用户'+mobile)
        db.session.add(user1)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库插入数据失败')
    return jsonify(errno=RET.OK, errmsg='注册成功')

@passport_blu.route('/login',methods=['POST'])
def login():
    params_dict = request.json
    mobile=params_dict.get('mobile')
    password = params_dict.get('passport')
    from information.utils.models import User
    from information.modules.index.views import data
    if not all([mobile,password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')
    user=User.query.filter_by(mobile=mobile,password_hash=encry_md5(password)).first()
    if not user:
        return jsonify(errno=RET.USERERR, errmsg='输入手机号或密码错误');
    data['user']=user.to_dict()
    return jsonify(errno=RET.OK, errmsg='登录成功')

@passport_blu.route('/logout',methods=['GET'])
def logout():
    data['user']=None
    data['is_collected']=None
    #return redirect(url_for('index.index'))
    return jsonify(errno=RET.OK,errmsg='注销成功')